import 'dart:io';

import 'package:check_app/dao/upload_dao.dart';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:path_provider/path_provider.dart';

class UploadImageUtil {
  // 获取压缩系数(file)
  getQualityByFile(File file) {
    return 2 * 1024 * 1024 * 100 ~/ file.lengthSync() < 100
        ? (2 * 1024 * 1024 * 100 ~/ file.lengthSync()).toInt()
        : 100;
  }

  // 获取压缩系数(bytes)
  getQualityByList(List<int> list) {
    return 2 * 1024 * 1024 * 100 ~/ list.length < 100
        ? (2 * 1024 * 1024 * 100 ~/ list.length).toInt()
        : 100;
  }

  // 在线-------------------------------------
  // 拍照
  Future getImageFromCamera() async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    var result = await FlutterImageCompress.compressWithFile(
      image.absolute.path,
      quality: getQualityByFile(image),
    );
    return await uploadImage(result);
  }

  Future uploadImage(_image) async {
    MultipartFile multipartFile = MultipartFile.fromBytes(
      _image,
      filename: 'imageName.jpg',
    );
    FormData formdata = FormData.fromMap({"file": multipartFile});
    try {
      var result = await UploadDao.upload(formdata);
      if (result.success) {
        return result.data.url;
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
    }
  }

  // 相册
  Future loadAssets(int number) async {
    List<Asset> imageList;
    try {
      imageList = await MultiImagePicker.pickImages(
        maxImages: number ?? 1,
        enableCamera: true,
        // selectedAssets: List<Asset>(),
        // cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
        // materialOptions: MaterialOptions(
        //   actionBarColor: "#abcdef",
        //   actionBarTitle: "Example App",
        //   allViewTitle: "All Photos",
        //   useDetailsView: false,
        //   selectCircleStrokeColor: "#000000",
        // ),
      );
    } on Exception catch (e) {
      imageList = null;
    }
    print(imageList);
    if (imageList != null) {
      return await uploadImageList(imageList);
    } else {
      return imageList;
    }
  }

  Future getImageList(_imageList) async {
    List multipartFileList = [];
    for (var item in _imageList) {
      ByteData byteData = await item.getByteData();
      List<int> imageData = byteData.buffer.asUint8List();
      var result = await FlutterImageCompress.compressWithList(
        imageData,
        quality: getQualityByList(imageData),
      );
      MultipartFile multipartFile = MultipartFile.fromBytes(
        result,
        filename: 'imageName.jpg',
      );
      multipartFileList.add(multipartFile);
    }
    return FormData.fromMap({
      'file': multipartFileList,
    });
  }

  Future uploadImageList(_imageList) async {
    FormData formdata = await getImageList(_imageList);
    try {
      var result = await UploadDao.uploadList(formdata);
      if (result.success) {
        return result.data.map((item) => item.url).toList();
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
    }
  }

  // 离线-------------------------------------
  // 本地储存拍照图片
  Future saveImageFromCamera() async {
    // 获取图片文件
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    // 压缩到2M以内，返回List<int> bytes数据
    var result = await FlutterImageCompress.compressWithFile(
      image.absolute.path,
      quality: getQualityByFile(image),
    );
    // 获取应用文档目录
    Directory documentsDir = await getApplicationDocumentsDirectory();
    String documentsPath = documentsDir.path;
    // 生成文件名
    String fileName = new DateTime.now().millisecondsSinceEpoch.toString();
    // 创建图片文件
    File file = new File('$documentsPath/$fileName');
    if (!file.existsSync()) {
      file.createSync();
    }
    // 写入文件
    File newFile = file..writeAsBytesSync(result);
    if (newFile.existsSync()) {
      // 返回路径
      return newFile.path;
    }
  }

  // 本地储存相册图片
  Future saveImageFromGallery(int number) async {
    // 相册内选择图片
    List<Asset> imageList;
    try {
      imageList = await MultiImagePicker.pickImages(
        maxImages: number ?? 1,
        enableCamera: true,
      );
    } on Exception catch (e) {
      imageList = null;
    }
    if (imageList == null) {
      return imageList;
    }

    // 遍历将每一张图片保存到本地目录
    List pathList = [];
    for (var item in imageList) {
      ByteData byteData = await item.getByteData();
      List<int> imageData = byteData.buffer.asUint8List();
      var result = await FlutterImageCompress.compressWithList(
        imageData,
        quality: getQualityByList(imageData),
      );
      // 获取应用文档目录
      Directory documentsDir = await getApplicationDocumentsDirectory();
      String documentsPath = documentsDir.path;
      // 生成文件名
      String fileName = new DateTime.now().millisecondsSinceEpoch.toString();
      // 创建图片文件
      File file = new File('$documentsPath/$fileName');
      if (!file.existsSync()) {
        file.createSync();
      }
      // 写入文件
      File newFile = file..writeAsBytesSync(result);
      if (newFile.existsSync()) {
        // 保存路径
        pathList.add(newFile.path);
      }
    }
    return pathList;
  }

  // 获取本地储存图片
  getImageFromDocumentsDirectory(String path) {
    File file = new File(path);
    try {
      return file..readAsBytesSync();
    } catch (e) {
      return null;
    }
  }

  // 上传离线图片
  Future uploadImageFromLocal(List<dynamic> pathList) async {
    List multipartFileList = [];
    for (var item in pathList) {
      File imageData = getImageFromDocumentsDirectory(item);
      MultipartFile multipartFile = await MultipartFile.fromFile(
        imageData.path,
        filename: 'imageName.jpg',
      );
      multipartFileList.add(multipartFile);
    }

    FormData formdata = FormData.fromMap({
      'file': multipartFileList,
    });
    try {
      var result = await UploadDao.uploadList(formdata);
      if (result.success) {
        for (var item in pathList) {
          File file = new File(item);
          file.deleteSync();
        }
        return result.data.map((item) => item.url).toList();
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
    }
  }

  Future getImageNetUrl(List<dynamic> pathList) async {
    List<dynamic> netList = [];
    List<dynamic> localList = [];

    for (var value in pathList) {
      if (value.indexOf('http') > -1) {
        netList.add(value);
      } else if (value.indexOf('/data/user') > -1) {
        localList.add(value);
      }
    }
    if (localList.length > 0) {
      List<dynamic> newUrl =
          await UploadImageUtil().uploadImageFromLocal(localList);
      for (var value in newUrl) {
        netList.add(value.toString());
      }
    }

    return netList;
  }
}
